package com.jianguozh.difs.framework.config;

import com.baomidou.mybatisplus.annotation.IEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * webmvc配置
 * 1、get 请求 参数为枚举类型
 * @author hanrs
 * @email 40736130@qq.com
 * @since 2022/6/12 16:43
 */
@Configuration
@Slf4j
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        log.info("addConverterFactory");
        registry.addConverterFactory(new EnumConverterFactory());
    }

    static class EnumConverterFactory implements ConverterFactory<String, IEnum>{
        @Override
        public <T extends IEnum> Converter<String, T> getConverter(Class<T> targetType) {
            return source -> {
                for (T e: targetType.getEnumConstants()) {
                    if (e.getValue().equals(source)) {
                        return e;
                    }
                }
                return null;
            };
        }
    }
}
